﻿using System.Diagnostics;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Input;

namespace LuckyCoding.Views;

public partial class TerminalView : UserControl
{
    private Process Terminal { get; }
    public TerminalView()
    {
        InitializeComponent();
        OutPutBlock = this.FindControl<TextBlock>("OutPutBlock");
        Terminal = new Process();
        Terminal.StartInfo.FileName = "cmd.exe";
        Terminal.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        Terminal.StartInfo.UseShellExecute = false;//是否使用操作系统shell启动
        Terminal.StartInfo.CreateNoWindow = true;
        Terminal.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
        Terminal.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
        Terminal.StartInfo.RedirectStandardError = true;//重定向标准错误输出
        Terminal.Start();
    }

    private void OrderOnKeyDown(object? sender, KeyEventArgs e)
    {
        if (e.Key != Key.Enter) return;
    }

    public async Task Run(string[] orders)
    {
        foreach (var o in orders)
            await Terminal.StandardInput.WriteLineAsync(o);//指令
        //Terminal.StandardInput.Close();
        var output = await Terminal.StandardOutput.ReadToEndAsync();
        OutPutBlock.Text = output;
    }

    public async Task Run(string s)
    {
        await Terminal.StandardInput.WriteLineAsync(s);//指令
        //Terminal.StandardInput.Close();
        var output = await Terminal.StandardOutput.ReadToEndAsync();
        OutPutBlock.Text = output;
    }
}